﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;

namespace PubSub.S2
{
    public class RedisSubMessageHandlerFactory
    {
        private static Dictionary<FuncTypeEnum, BaseHandler> cache = new Dictionary<FuncTypeEnum, BaseHandler>();


        public static void Init()
        {
            //获取所有继承BaseHandler的实现类
            var ts = Assembly.GetCallingAssembly().GetTypes().Where(e => e.BaseType == typeof(BaseHandler));
            if (ts != null && ts.Any())
            {
                var channels = FuncTypeFactory.ChannelCache;
                foreach (var type in ts)
                {
                    var obj = Activator.CreateInstance(type);
                    //反射获取其FuncType属性值
                    var funcTypePro = type.GetProperty("FuncType", BindingFlags.Public | BindingFlags.GetProperty);
                    var funcTypeObj = funcTypePro?.GetValue(obj);
                    var funcType = funcTypeObj as FuncTypeEnum?;
                    if (funcType.HasValue && FuncTypeFactory.IsValidType((int) funcType) &&
                        !cache.ContainsKey(funcType.Value))
                    {
                        cache.Add(funcType.Value, obj as BaseHandler);
                    }
                }
            }

            cache.Add(FuncTypeEnum.Default, new BaseHandler());
        }


        public static BaseHandler GetHandler(FuncTypeEnum type)
        {
            if (!cache.ContainsKey(type)) return null;

            return cache[type];
        }
    }
}